package com.genghis.ptas.posts.dao.impl;

import com.genghis.core.page.dao.PageDao;
import com.genghis.core.page.entity.Page;
import com.genghis.core.page.entity.PageParameter;
import com.genghis.ptas.posts.dao.PostsDao;
import com.genghis.ptas.posts.entity.Posts;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;

/**
 *
 * @author yutong
 * @version 1.0.1
 */

@Repository("postsDao")
public class PostsDaoImpl extends PageDao implements PostsDao {

    @Override
    public int addPosts(Posts posts) {
        String sql="INSERT INTO posts(topic,post_person_id,post_time) VALUES(:topic,:postPersonId,:postTime)";
        KeyHolder keyHolder=new GeneratedKeyHolder();
        getNamedParameterJdbcTemplate().update(sql,new BeanPropertySqlParameterSource(posts),keyHolder);
        return keyHolder.getKey().intValue();
    }

    @Override
    public Page<Posts> findPostsPageList(PageParameter pageParameter, Posts posts) {
        StringBuilder sql=new StringBuilder("SELECT p.*,u.`login_name` showPostPerson FROM posts p,user_info u WHERE p.`post_person_id`=u.`id`");
        if(posts.getTopic()!=null&&!posts.getTopic().equals("")){
           sql.append(" AND topic like '%").append(posts.getTopic().trim()).append("%'");
        }
        return queryForPage(pageParameter,sql.toString(),new BeanPropertySqlParameterSource(posts),new BeanPropertyRowMapper<Posts>(Posts.class));
    }

    @Override
    public Posts findPostById(int id) {
        String sql="SELECT * FROM posts p WHERE p.`id`="+id;
        return getJdbcTemplate().queryForObject(sql.toString(), new BeanPropertyRowMapper<Posts>(Posts.class));
    }

    @Override
    public int findReplyNumById(int postId) {
        String sql="SELECT COUNT(p.`post_id`) replyNum FROM post_reply p WHERE p.`post_id`="+postId;
        return getJdbcTemplate().queryForInt(sql);
    }

    @Override
    public int delPosts(int postId) {
        String sql="DELETE FROM posts where id=?";
        return getJdbcTemplate().update(sql,postId);
    }
}